package com.spring.rabbitmq.helloworld;

import com.rabbitmq.client.*;
import com.spring.rabbitmq.utils.RabbitMQUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author: lzx
 * @Data: 2021/04/26/16:29
 * @Description：
 */
@Slf4j
public class Customer {
    @SneakyThrows
    public static void main(String[] args) {
/*        //创建连接工厂对象
        ConnectionFactory factory = new ConnectionFactory();
        //设置连接主机
        factory.setHost("ali");
        //设置连接端口
        factory.setPort(5672);
        //设置连接用户名、密码
        factory.setUsername("lingzx");
        factory.setPassword("lingzx");
        //设置连接虚拟主机
        factory.setVirtualHost("/elasticsearch");
        //获取连接对象
        Connection connection = factory.newConnection();*/

        //通过工具获取连接
        Connection connection = RabbitMQUtils.getConnection();
        Channel channel = connection.createChannel();
        String queue = "bb";
        channel.queueDeclare(queue, true, false, true, null);
        //直连
        direct(channel,queue);
        //work queues 任务模式
//        work_queue(channel,queue);

    }

    @SneakyThrows
    private static void direct(Channel channel,String queue) {
        channel.basicConsume(queue, true, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者：" + new String(body));
            }
        });
    }

    @SneakyThrows
    private static void work_queue(Channel channel,String queue) {
        channel.basicConsume(queue, true, new DefaultConsumer(channel) {
            @SneakyThrows
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                Thread.sleep(1000);
                log.info("消费者：{}", new String(body));
            }
        });
    }


}
